package com.cantor.example;

import cn.hutool.core.lang.Console;
import com.cantor.consumer.future.FuturesKeeper;
import com.cantor.consumer.start.ConsumerNettyKeeper;
import com.cantor.core.center.RegistrationCenter;
import com.cantor.core.center.impl.ZooKeeperRegistrationCenter;
import com.cantor.core.message.CantorRequestMessage;
import io.netty.channel.Channel;

import java.util.concurrent.CompletableFuture;

/**
 * 测试客户端发送RPC请求
 */
public class TestSendReq {

    private RegistrationCenter center;

    private String HOST = "192.168.199.109";

    private int PORT = 8000;

    private void init() throws InterruptedException {
        center = new ZooKeeperRegistrationCenter().setNamespace("cantor");
        center.run();
        ConsumerNettyKeeper.addConnection(HOST, PORT);
    }

    private CantorRequestMessage buildReq(long sequenceId) {
        CantorRequestMessage req = CantorRequestMessage.builder()
                .interfaceName("com.cantor.example.service.HelloService")
                .serviceVersion("")
                .methodName("cal")
                .parameterTypes(new Class[]{int.class, int.class})
                .parameterValue(new Object[]{1, 1})
                // .returnType(int.class)
                .build();
        req.setSequenceId(sequenceId);
        return req;
    }


    public void test() throws Exception {
        // 初始化注册中心,Netty连接等
        init();
        // 获取一个Channel
        Channel ch = ConsumerNettyKeeper.getChannel(HOST, PORT);

        // 开始压测
        int nCycle = 10; // 周期数
        int times = 100; // 初始次数
        int increment = 100; // 增量
        long globalStart = System.currentTimeMillis();
        for (int i = 0; i < nCycle; i++) {
            long cycleStart = System.currentTimeMillis();
            for (int j = 0; j < times; j++) {
                long sequenceId = center.getSequenceId();
                ch.writeAndFlush(buildReq(sequenceId)); // 发送
                FuturesKeeper.record(sequenceId, new CompletableFuture()).join(); // 等待
            }
            long cycleEnd = System.currentTimeMillis();
            Console.log("第{}个周期,共{}次RPC调用,耗时{}ms", (i + 1), times, (cycleEnd - cycleStart));
            times += increment;
        }
        long globalEnd = System.currentTimeMillis();
        Console.error("总体,耗时{}ms", (globalEnd - globalStart));
    }

    public static void main(String[] args) throws Exception {
        TestSendReq instance1 = new TestSendReq();
        instance1.test();
    }

}
